var express = require('express');
var http = require('http');
var urlencode=require('urlencode');
var urldecode=require('urldecode');
var crypto=require('crypto');
var redis=require('redis');
var client=redis.createClient();

var monk=require('monk');
var db=monk('localhost:27017/usercollection');
var collection=db.get('usercollection');
var mescollection=db.get('messagecollection');
var returnMessage=db.get('returnMessage');
var upMessage=db.get('upMessage');

var wjxt=require('../routes/wjxt');
var router = express.Router();

client.on("error", function(err) {
  console.log("Error " + err);
});

Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: '短信管理系统' });
});


router.get('/login',function(req,res,next){
  res.render('login',{title:'短信管理系统' });
});

router.get('/send',function(req,res,next){
  res.render('send',{title:'短信管理系统' });
});

router.post('/',function(req,res,next){
  console.log('go into post...');
  var clientdata=req.body;
  console.log('clientdata', clientdata);
  console.log(clientdata.appId!=undefined&&clientdata.content!=undefined&&clientdata.mobile!=undefined&&clientdata.code!=undefined);
  var date=new Date();
  var msg='',status='';
  if(clientdata.appId!=undefined&&clientdata.content!=undefined&&clientdata.mobile!=undefined&&clientdata.code!=undefined) {
    var code = clientdata.code;
    var mobile = clientdata.mobile;
    var decode=decodeURI(clientdata.content);
    var content = urlencode(decode);
    var re=/%20/g;
    var con = content.replace(re,"+");
    var regBox = {
      regMobile: /^0?1[3|4|5|7|8]\d{9}$/
    };
    var mflag = regBox.regMobile.test(mobile);
    collection.findOne({appId: clientdata.appId}, function (err, data) {
      if (err) throw err;
      checkStatus(data);
    });
    function checkStatus(result) {
      if (result != null) {
        if (result.status != '1') {
          console.log("appId is not in period ...");
          msg = '商户号超过合同期限';
          status = -22;
          res.send({'msg': msg, 'status': status, 'time': date.Format('yyyy-MM-dd hh:mm:ss.S')});
          return false;
        }
        var codestr = result.secretKey + mobile + con;
        var md5 = crypto.createHash('md5');
        md5.update(codestr);
        var d = md5.digest('hex');
        console.log("content:"+con);
        console.log("code:"+d);
        if(!mflag){
          console.log("wrong mobile type ...");
          msg='手机号码格式不正确';
          status=-12;
          res.send({'msg':msg,'status':status,'time':date.Format('yyyy-MM-dd hh:mm:ss.S')});
        }else if(d!=code){
          console.log("wrong code ...");
          msg='code验证失败，请检查密码及code生成规则是否正确';
          status=-11;
          res.send({'msg':msg,'status':status,'time':date.Format('yyyy-MM-dd hh:mm:ss.S')});
        }else{
          client.get(mobile, function (err, reply) {
            if (reply) {
              console.log("mobile is repeat in 30s ...");
              msg = '请30s后重新获取';
              status = -13;
              res.send({'msg': msg, 'status': status, 'time': date.Format('yyyy-MM-dd hh:mm:ss.S')});
            } else {
              console.log("success ...");
              client.set(mobile, '0');
              client.expire(mobile, 30);
	          clientdata.content=decode;
              // wjxt.sendContent(clientdata);
              msg = 'SUCCESS';
              status = 0;
              res.send({'msg': msg, 'status': status, 'time': date.Format('yyyy-MM-dd hh:mm:ss.S')});
            }
          });
        }
      } else {
        console.log("wrong appId ...");
        msg = '商户号错误';
        status = -21;
        res.send({'msg': msg, 'status': status, 'time': date.Format('yyyy-MM-dd hh:mm:ss.S')});
      }
    }
  }else{
    console.log("params exist empty ...");
    msg='参数不完整';
    status=-23;
    res.send({'msg':msg,'status':status,'time':date.Format('yyyy-MM-dd hh:mm:ss.S')});
  }
});


router.post('/send',function(req,res,next) {

  var clientdata=req.body;
  var date = new Date();
  var msg='',status='';
  if(clientdata.appId!=undefined&&clientdata.content!=undefined&&clientdata.mobile!=undefined&&clientdata.code!=undefined) {
    var code = clientdata.code;
    var mobiles = clientdata.mobile.split(",");
    var content = urlencode(clientdata.content);
    var re=/%20/g;
    var con = content.replace(re,"+");
    var regMobile= /^(1[3|4|5|7|8]\d{9})(,(1[3|4|5|7|8]\d{9}))*$/;
    var mflag =regMobile.test(clientdata.mobile);
    collection.findOne({appId: clientdata.appId}, function (err, data) {
      if (err) throw err;
      checkStatus(data);
    });
    function checkStatus(result) {
      if (result != null) {
        if (result.status != '1') {
          msg = '商户号超过合同期限';
          status = -22;
          res.send({'msg': msg, 'status': status, 'time': date.Format('yyyy-MM-dd hh:mm:ss.S')});
          return false;
        }
        var codestrAll = result.secretKey + mobiles + con;
        var md5 = crypto.createHash('md5');
        md5.update(codestrAll);
        var d = md5.digest('hex');
        console.log("code+_____"+d);
        if(!mflag){
          msg='手机号码格式不正确';
          status=-12;
          res.send({'msg':msg,'status':status,'time':date.Format('yyyy-MM-dd hh:mm:ss.S')});
        }else if(d!=code){
          msg='code验证失败，请检查密码及code生成规则是否正确';
          status=-11;
          res.send({'msg':msg,'status':status,'time':date.Format('yyyy-MM-dd hh:mm:ss.S')});
        }else{
          mobiles.forEach(function(mobile){
            client.get(mobile, function (err, reply) {
               if(!reply){
                var codestr = result.secretKey + mobile + con;
                var md5One = crypto.createHash('md5');
                md5One.update(codestr);
                var dOne = md5One.digest('hex');
                var postData={'appId':clientdata.appId,'content':clientdata.content,'mobile':mobile,'code':dOne};
                client.set(mobile, '0');
                client.expire(mobile, 30);
                console.log(mobile);
                // wjxt.sendContent(postData);
              }
            });
          });
          msg = 'SUCCESS';
          status = 0;
          res.send({'msg': msg, 'status': status, 'time': date.Format('yyyy-MM-dd hh:mm:ss.S')});
        }
      } else {
        msg = '商户号错误';
        status = -21;
        res.send({'msg': msg, 'status': status, 'time': date.Format('yyyy-MM-dd hh:mm:ss.S')});
      }
    }
  }else{
    msg='参数不完整';
    status=-23;
    res.send({'msg':msg,'status':status,'time':date.Format('yyyy-MM-dd hh:mm:ss.S')});
  }
});

router.post('/status',function(req,res,next){
   var list=req.body.list;
  if (list.length > 0) {
    list.forEach(function(item){
      returnMessage.insert({taskId: item.taskId,status: item.status,remark: item.remakr,item:item},function (err, data) {
        if (err) throw err;
      });
      mescollection.update({taskId:item.taskId},{$set:{returnC:item.status,remark:item.remakr}},function(err,data){
        if(err) throw err;
      });
      if(item.status==1){
        mescollection.findOne({taskId: item.taskId}, function (err, data) {
          if(err) throw err;
          if(data!=null){
            mescollection.update({taskId: item.taskId}, {$set: {status: 0}},function(err,data){
              if(err) throw err;
            });
          }
        });
      }
    });
  }
  res.send('{"status":200}');
});

router.post('/upmsg_wlw',function(req,res,next){
  var date=new Date();
  var result=req.query;
  var returnM='';
  var status=1;
  var appId='';
  collection.findOne({checkContent:result.content},function(err,data){
    if(data!=null){
      appId=data.appId;
    }
    upMessage.insert({appId:appId,mobile:result.mobile,content:result.content,recvTime:result.recv_time},function(err,data){
          if(err) throw err;
          if(appId==''){
            returnM="发送内容不匹配，验证不通过";
            status=-1;
          }else{
            returnM="验证通过";
          }
          var postParam={"status":status,"mobile":result.mobile,"message":returnM,"time":date.Format('yyyy-MM-dd hh:mm:ss')};
          //res.send(postParam);
        }
    );
  });
  res.send();
});

module.exports = router;
